﻿/*
 * 作者：杨云
 * 功能描述：定义系统所需要的公共访问
 * 时间：2017-12-1
 * 修改人：
 * 修改时间：
 *
 */

using System.Text;
using System.Security.Cryptography;
using System;
using System.Data;
using System.Windows.Forms;
using System.Text.RegularExpressions;

using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using System.Data.OleDb;

namespace Common
{
    public class AppMethod
    {

        #region 加密
        /// <summary>
        /// MD5加密，返回加密后的字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>经MD5算法加密后的字符串</returns>
        private static string MD5Encrypt(string source)
        {
            string sPwd = "";

            MD5 md5 = MD5.Create();
            byte[] bytesTemp = md5.ComputeHash(Encoding.UTF8.GetBytes(source));

            for (int i = 0; i < bytesTemp.Length; i++)
            {
                sPwd = sPwd + bytesTemp[i].ToString("X");
            }

            return sPwd;
        }

        /// <summary>
        /// SHA1加密，返回加密后的字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>经SHA1算法加密后的字符串</returns>
        private static string SHA1Encrypt(string source)
        {
            string sPwd = "";

            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytesTemp = UTF8Encoding.Default.GetBytes(source);
            byte[] bytesResult = sha1.ComputeHash(bytesTemp);

            for (int i = 0; i < bytesResult.Length; i++)
            {
                sPwd = sPwd + bytesResult[i].ToString("X");
            }

            return sPwd;
        }

        /// <summary>
        /// 系统用加密算法(由MD5和SHA1联合加密)，返回加密后的字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>算法加密后的字符串</returns>
        public static string Encrypt(string source)
        {
            string sPwd = "";
            sPwd = MD5Encrypt(SHA1Encrypt(source + "Software"));
            return sPwd;
        }

        #endregion

        #region 提示信息
        /// <summary>
        /// 显示一般的提示信息
        /// </summary>
        /// <param name="message">提示信息</param>
        public static DialogResult ShowTips(string message)
        {
            return MessageBox.Show(message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 显示警告信息
        /// </summary>
        /// <param name="message">警告信息</param>
        public static DialogResult ShowWarning(string message)
        {
            return MessageBox.Show(message, "警告信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        /// <summary>
        /// 显示错误信息
        /// </summary>
        /// <param name="message">错误信息</param>
        public static DialogResult ShowError(string message)
        {
            return MessageBox.Show(message, "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 显示询问用户信息，并显示错误标志
        /// </summary>
        /// <param name="message">错误信息</param>
        public static DialogResult ShowYesNoAndError(string message)
        {
            return MessageBox.Show(message, "错误信息", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 显示询问用户信息，并显示提示标志
        /// </summary>
        /// <param name="message">错误信息</param>
        public static DialogResult ShowYesNoAndTips(string message)
        {
            return MessageBox.Show(message, "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 显示询问用户信息，并显示警告标志
        /// </summary>
        /// <param name="message">警告信息</param>
        public static DialogResult ShowYesNoAndWarning(string message)
        {
            return MessageBox.Show(message, "警告信息", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
        }

        /// <summary>
        /// 显示询问用户信息，并显示提示标志
        /// </summary>
        /// <param name="message">错误信息</param>
        public static DialogResult ShowYesNoCancelAndTips(string message)
        {
            return MessageBox.Show(message, "提示信息", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 显示一个YesNo选择对话框
        /// </summary>
        /// <param name="prompt">对话框的选择内容提示信息</param>
        /// <returns>如果选择Yes则返回true，否则返回false</returns>
        public static bool ConfirmYesNo(string prompt)
        {
            return MessageBox.Show(prompt, "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;
        }


        /// <summary>
        /// 显示一个YesNoCancel选择对话框
        /// </summary>
        /// <param name="prompt">对话框的选择内容提示信息</param>
        /// <returns>返回选择结果的的DialogResult值</returns>
        public static DialogResult ConfirmYesNoCancel(string prompt)
        {
            return MessageBox.Show(prompt, "确认", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
        }

        #endregion

        #region Dev控件列表导出数据
        /// <summary> 导出GridContro列表数据 </summary>
        /// <param name="mDataGrid">GridView Id</param>
        /// <param name="mDataControl">GridControl Id</param>
        public static void ExportDataToExcel(GridView mDataGrid, GridControl mDataControl )
        {
            try
            {
                if (mDataGrid.RowCount == 0)
                {
                    AppMethod.ShowTips("该表中没有数据，不能导出");
                }
                using (SaveFileDialog saveFD = new SaveFileDialog())
                {
                    saveFD.Filter = "导出Excel(*.xls)|*.xls";
                    saveFD.FilterIndex = 0;
                    saveFD.RestoreDirectory = true;
                    saveFD.CreatePrompt = true;
                    saveFD.Title = "导出文件保存路径";
                    //默认文件名
                    saveFD.FileName = "";
                    if (saveFD.ShowDialog() == DialogResult.OK)
                    {
                        mDataControl.ExportToXls(saveFD.FileName);
                        AppMethod.ShowTips("导出成功");
                    }
                }
            }
            catch (Exception ex)
            {
                AppMethod.ShowError(ex.Message);
            }
        }

        #endregion 

        #region 其他

        /// <summary> 判断所输入的数字是否为空，为空则以NULL代替
        /// </summary>
        /// <param name="sValue">输入的数据</param>
        /// <returns>返回替换后的数据</returns>
        public static object SetNUllValue(string sValue)
        {
            object obj;
            if (sValue == "")
                obj = DBNull.Value;
            else
                return sValue;
            return obj;

        }

        /// <summary>
        /// 判断输入的是否是合法的实数
        /// </summary>
        /// <param name="txt">验证的文本</param>
        /// <returns></returns>
        public static bool IsNumberic(string txt)
        {
            string temp =@"^?\d+(\.\d+)?$";
            Regex rex = new Regex(temp);

            if (rex.IsMatch(txt))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 判断输入的是否是合法的数
        /// </summary>
        /// <param name="txt">验证的文本</param>
        /// <returns></returns>
        public static bool IsNumber(string txt)
        {
            string temp = @"^[0-9]*$";
            Regex rex = new Regex(temp);

            if (rex.IsMatch(txt))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 导入和导出excel文件


        /// <summary>
        /// 导入excel文件
        /// </summary>
        /// <param name="gridControl">导入到所显示的gridControl</param>
        /// <returns>导入成功为 true；失败为false</returns>
        public static bool ImportFile(GridControl gridControl)
        {
            bool flag = false;
            DataSet ds = new DataSet();

            try
            {
                ds = GetDataFromExcelByConn(true).Copy();
                gridControl.DataSource = null;
                gridControl.DataSource = ds.Tables[0];
                flag = true;
                MessageBox.Show("读取数据成功");
            }
            catch (Exception ex)
            {
                flag = false;
                MessageBox.Show("读取数据失败", ex.Message);
            }
            return flag;
        }

        /// <summary>
        /// 导出excel文件
        /// </summary>
        /// <param name="gridView">将要导出的gridView</param>
        /// <returns>导入成功为 true；失败为false</returns>
        public static bool ExportFile(GridView gridView)
        {
            bool flag = false;
            try
            {
                if (gridView.RowCount == 0)
                {
                    MessageBox.Show("该表中没有数据，不能导出！", "提示");
                }
                using (SaveFileDialog saveFD = new SaveFileDialog())
                {
                    saveFD.Filter = "导出Excel(*.xls)|*.xls";
                    saveFD.FilterIndex = 0;
                    saveFD.RestoreDirectory = true;
                    saveFD.CreatePrompt = true;
                    saveFD.Title = "导出文件保存路径";
                    //默认文件名
                    saveFD.FileName = "";
                    if (saveFD.ShowDialog() == DialogResult.OK)
                    {
                        DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
                        gridView.ExportToXls(saveFD.FileName);
                        MessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK);
                        flag = true;
                    }
                }
            }
            catch (Exception ex)
            {
                flag = false;
                MessageBox.Show(ex.Message, "提示");
            }
            return flag;
        }

        private static DataSet GetDataFromExcelByConn(bool hasTitle = false)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
            openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            openFile.Multiselect = false;
            if (openFile.ShowDialog() == DialogResult.Cancel) return null;
            var filePath = openFile.FileName;
            string fileType = System.IO.Path.GetExtension(filePath);
            if (string.IsNullOrEmpty(fileType)) return null;

            using (DataSet ds = new DataSet())
            {
                string strCon = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;" +
                                "Extended Properties=\"Excel {1}.0;HDR={2};IMEX=1;\";" +
                                "data source={3};",
                                (fileType == ".xls" ? 4 : 12), (fileType == ".xls" ? 8 : 12), (hasTitle ? "Yes" : "NO"), filePath);
                string strCom = " SELECT * FROM [Sheet1$]";
                using (OleDbConnection myConn = new OleDbConnection(strCon))
                using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn))
                {
                    myConn.Open();
                    myCommand.Fill(ds);
                }
                if (ds == null || ds.Tables.Count <= 0) return null;

                // textBox1.Text = ds.ToString();
                return ds;
            }
        }

        #endregion









    }
}
